package com.king.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * 自定义服务器处理器
 * @author unidentifiable
 * @date 2021-03-06
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext chc, HttpObject msg) throws Exception {
        // 判断是不是 httprequest 请求
        if (msg instanceof HttpRequest){
            System.out.println("msg 类型 -> " + msg.getClass());
            System.out.println("客户端地址 -> " + chc.channel().remoteAddress());

            HttpRequest request = (HttpRequest) msg;
            URI uri = new URI(request.getUri());
            if (uri.getPath().indexOf(".ioc") != -1){
                return;
            }

            // 回复信息
            ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器", CharsetUtil.UTF_8);

            // 构造一个 httpresponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 返回
            chc.writeAndFlush(response);
        }
    }
}
